package org.celery.modules.shopStatics.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import lombok.SneakyThrows;
import org.apache.commons.codec.Charsets;
import org.celery.modules.shop.entity.Shop;
import org.celery.modules.shop.service.IShopService;
import org.celery.modules.shopStatics.excel.ShopStaticsDayExcel;
import org.celery.modules.shopStatics.excel.ShopStaticsDayImportListener;
import org.celery.modules.ticket.entity.Ticket;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.excel.UserImportListener;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.celery.modules.shopStatics.entity.ShopStaticsDay;
import org.celery.modules.shopStatics.vo.ShopStaticsDayVO;
import org.celery.modules.shopStatics.wrapper.ShopStaticsDayWrapper;
import org.celery.modules.shopStatics.service.IShopStaticsDayService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 店铺日数据统计表 控制器
 *
 * @author Celery
 * @since 2023-08-26
 */
@RestController
@AllArgsConstructor
@RequestMapping("celery-shop-statics-day/shop-statics-day")
@Api(value = "店铺日数据统计表", tags = "店铺日数据统计表接口")
public class ShopStaticsDayController extends BladeController {

	private final IShopStaticsDayService shopStaticsDayService;
	private final IShopService shopService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入shopStaticsDay")
	public R<ShopStaticsDayVO> detail(ShopStaticsDay shopStaticsDay) {
		ShopStaticsDay detail = shopStaticsDayService.getOne(Condition.getQueryWrapper(shopStaticsDay));
		return R.data(ShopStaticsDayWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 店铺日数据统计表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入shopStaticsDay")
	public R<IPage<ShopStaticsDayVO>> list(ShopStaticsDay shopStaticsDay, Query query,
										   @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate dateStart,
										   @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate dateEnd,
										   @RequestParam(required = false) String shopName,
										   @RequestParam(required = false) String tenantId,
										   BladeUser user
	) {
		QueryWrapper<ShopStaticsDay> queryWrapper = Condition.getQueryWrapper(shopStaticsDay);
		if (Func.isNotEmpty(dateStart) && Func.isNotEmpty(dateEnd)) {
			queryWrapper.lambda().between(ShopStaticsDay::getDate, dateStart, dateEnd);
		}
		if (Func.isNotEmpty(shopName)) {
			List<Shop> shopList = shopService.list(Wrappers.<Shop>lambdaQuery().like(Shop::getResourceOwner, shopName));
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}
			List<Long> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
			queryWrapper.lambda().in(ShopStaticsDay::getShopId, shopIdList);
		}
		if (Func.isNotEmpty(tenantId)) {
			List<Shop> shopList = shopService.list(Wrappers.<Shop>lambdaQuery().eq(Shop::getTenantId, tenantId));
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}
			List<Long> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
			queryWrapper.lambda().in(ShopStaticsDay::getShopId, shopIdList);
		}
		if(!user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) || (!user.getRoleName().contains("administrator") && !user.getRoleName().contains("s_admin") && !user.getRoleName().contains("caiwu") && !user.getRoleName().contains("fake_boss"))) {
			List<Shop> shopList = shopService.authList(user);
			if (Func.isEmpty(shopList)) {
				return R.data(new Page<>());
			}

			List<Long> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
			queryWrapper.lambda().in(ShopStaticsDay::getShopId, shopIdList);
		}
		queryWrapper.lambda().orderByDesc(ShopStaticsDay::getDate).orderByDesc(ShopStaticsDay::getCreateTime);
		IPage<ShopStaticsDay> pages = shopStaticsDayService.page(Condition.getPage(query), queryWrapper);
		return R.data(ShopStaticsDayWrapper.build().pageVO(pages));
	}


	/**
	 * 自定义分页 店铺日数据统计表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入shopStaticsDay")
	public R<IPage<ShopStaticsDayVO>> page(ShopStaticsDayVO shopStaticsDay, Query query) {
		IPage<ShopStaticsDayVO> pages = shopStaticsDayService.selectShopStaticsDayPage(Condition.getPage(query), shopStaticsDay);
		return R.data(pages);
	}

	/**
	 * 新增 店铺日数据统计表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入shopStaticsDay")
	public R save(@Valid @RequestBody ShopStaticsDay shopStaticsDay) {
		return R.status(shopStaticsDayService.save(shopStaticsDay));
	}

	/**
	 * 修改 店铺日数据统计表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入shopStaticsDay")
	public R update(@Valid @RequestBody ShopStaticsDay shopStaticsDay) {
		return R.status(shopStaticsDayService.updateById(shopStaticsDay));
	}

	/**
	 * 新增或修改 店铺日数据统计表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入shopStaticsDay")
	public R submit(@Valid @RequestBody ShopStaticsDay shopStaticsDay) {
		if (Func.isEmpty(shopStaticsDay.getId())) {
			QueryWrapper<ShopStaticsDay> queryWrapper = new QueryWrapper<>();
			queryWrapper.lambda().eq(ShopStaticsDay::getShopId, shopStaticsDay.getShopId()).eq(ShopStaticsDay::getDate, shopStaticsDay.getDate());
			List<ShopStaticsDay> dataList = shopStaticsDayService.list(queryWrapper);
			if (Func.isNotEmpty(dataList)) {
				throw new ServiceException("请勿重复添加当日数据, 请检查所选店铺或日期!");
			}
		}
		return R.status(shopStaticsDayService.saveOrUpdate(shopStaticsDay));
	}

	
	/**
	 * 删除 店铺日数据统计表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(shopStaticsDayService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 导出日统计数据
	 */
	@SneakyThrows
	@GetMapping("export-shop-statics-day")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "导出日统计数据")
	public void exportShopStaticsDay(@ApiIgnore @RequestParam Map<String, Object> shopStaticsDay, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<ShopStaticsDay> queryWrapper = Condition.getQueryWrapper(shopStaticsDay, ShopStaticsDay.class);
		if(!bladeUser.getRoleName().equals("administrator") && !bladeUser.getRoleName().equals("s_admin")) {
			List<Shop> shopList = shopService.list(Wrappers.<Shop>lambdaQuery().eq(Shop::getResourceOwner, bladeUser.getUserName()));
			if (Func.isEmpty(shopList)) {
				queryWrapper.lambda().isNull(ShopStaticsDay::getShopId);
			} else {
				List<Long> shopIds = shopList.stream().map(Shop::getId).collect(Collectors.toList());
				queryWrapper.lambda().in(ShopStaticsDay::getShopId, shopIds);
			}
		}
		queryWrapper.lambda().eq(ShopStaticsDay::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<ShopStaticsDayExcel> list = shopStaticsDayService.exportShopStaticsDay(queryWrapper);
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(Charsets.UTF_8.name());
		String fileName = URLEncoder.encode("店铺统计数据导出", Charsets.UTF_8.name());
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		List<String> shopNameList = list.stream().map(ShopStaticsDayExcel::getShopName).distinct().collect(Collectors.toList());

		ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).build();
		for (int i = 0; i < shopNameList.size(); i++) {
			String sheetName = shopNameList.get(i);
			sheetName = sheetName.replace(":", "_");
			WriteSheet sheet = EasyExcel.writerSheet(i, sheetName).head(ShopStaticsDayExcel.class).build();

			List<ShopStaticsDayExcel> sheetList = new ArrayList<>();
			int finalI = i;
			list.forEach(item -> {
				if (item.getShopName().equals(shopNameList.get(finalI))) {
					sheetList.add(item);
				}
			});

			excelWriter.write(sheetList, sheet);
		}
		excelWriter.finish();
	}

	/**
	 * list 店铺日数据统计列表
	 */
	@GetMapping("/list-for-compare")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "list", notes = "传入shopStaticsDay")
	public R<List<ShopStaticsDayVO>> listForCompare(ShopStaticsDay shopStaticsDay,
										   @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate dateStart,
										   @RequestParam(required = false) @DateTimeFormat(pattern="yyyy-MM-dd") LocalDate dateEnd,
										   @RequestParam(required = false) String shopIds,
										   BladeUser user
	) {
		QueryWrapper<ShopStaticsDay> queryWrapper = Condition.getQueryWrapper(shopStaticsDay);
		if (Func.isNotEmpty(dateStart) && Func.isNotEmpty(dateEnd)) {
			queryWrapper.lambda().between(ShopStaticsDay::getDate, dateStart, dateEnd);
		}
		if (Func.isNotEmpty(shopIds)) {
			queryWrapper.lambda().in(ShopStaticsDay::getShopId, Func.toLongList(shopIds));
		}
		if(!user.getTenantId().equals(BladeConstant.ADMIN_TENANT_ID) || (!user.getRoleName().contains("administrator") && !user.getRoleName().contains("s_admin") && !user.getRoleName().contains("caiwu") && !user.getRoleName().contains("fake_boss"))) {
			List<Shop> shopList = shopService.authList(user);
			if (Func.isEmpty(shopList)) {
				return R.data(new ArrayList<>());
			}

			List<Long> shopIdList = shopList.stream().map(Shop::getId).collect(Collectors.toList());
			queryWrapper.lambda().in(ShopStaticsDay::getShopId, shopIdList);
		}
		queryWrapper.lambda().orderByDesc(ShopStaticsDay::getDate).orderByDesc(ShopStaticsDay::getCreateTime);
		List<ShopStaticsDay> list = shopStaticsDayService.list(queryWrapper);
		return R.data(ShopStaticsDayWrapper.build().listVO(list));
	}

	/**
	 * 导入统计信息
	 */
	@PostMapping("import-data")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "导入统计信息", notes = "传入excel")
	public R importData(MultipartFile file, Integer isCovered) {
		String filename = file.getOriginalFilename();
		if (StringUtils.isEmpty(filename)) {
			throw new RuntimeException("请上传文件!");
		}
		if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
			throw new RuntimeException("请上传正确的excel文件!");
		}
		InputStream inputStream;
		try {
			ShopStaticsDayImportListener importListener = new ShopStaticsDayImportListener(shopStaticsDayService);
			inputStream = new BufferedInputStream(file.getInputStream());
			ExcelReaderBuilder builder = EasyExcel.read(inputStream, ShopStaticsDayExcel.class, importListener);
			builder.doReadAll();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return R.success("操作成功");
	}

	/**
	 * 导出模板
	 */
	@SneakyThrows
	@GetMapping("export-template")
	@ApiOperationSupport(order = 11)
	@ApiOperation(value = "导出模板")
	public void exportUser(HttpServletResponse response) {
		List<UserExcel> list = new ArrayList<>();
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(Charsets.UTF_8.name());
		String fileName = URLEncoder.encode("店铺访客数据模板", Charsets.UTF_8.name());
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), ShopStaticsDayExcel.class).sheet("店铺访客数据").doWrite(list);
	}
}
